import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '../router';
import { useUserStore } from '../stores/user';

export const baseURL ='http://127.0.0.1:3000/api';
export const request = axios.create({
  baseURL,
  timeout: 30000,
});
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    const store = useUserStore();
    if (store.user?.token && config.headers) {
      config.headers.token = store.user.token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  },
);

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    const store = useUserStore();
    if (response.data.code != '0000') {
      // 提示错误
      ElMessage.error(response.data.msg);
      // 将响应数据返回成错误
      if (response?.data.code == 401) {
        store.delUser(); // 删除token
        ElMessage.error('登录已过期,请重新登录');
        router.push(`/login`);
      }
      return Promise.reject(response.data);
    }
    return response.data;
  },
  function (error) {
    const store = useUserStore();
    console.dir('err', error.response);
    if (error.response?.code == 401) {
      store.delUser(); // 删除token
      ElMessage.error('登录已过期,请重新登录');
      router.push(`/login?returnUrl=${router.currentRoute.value.fullPath}`);
    }
    //网络超时异常处理
    if (
      error.code === 'ECONNABORTED' ||
      error.message === 'Network Error' ||
      error.message.includes('timeout')
    ) {
      ElMessage.error('请求超时,请稍后重试');
    }
    console.dir(error.response);
    return Promise.reject(error);
  },
);
